package com.smart.translator.util;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.util.Log;

public class WavUtil {
    private static final String TAG = "WavUtil";
    
    public static byte[] pcmToWav(byte[] pcm, int sampleRate, int channels, int bitsPerSample) {
        if (pcm == null || pcm.length == 0) {
            Log.e(TAG, "PCM数据为空，无法生成WAV");
            return new byte[0];
        }
        
        int totalDataLen = pcm.length + 36;
        int byteRate = sampleRate * channels * bitsPerSample / 8;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        
        try {
            Log.d(TAG, "开始生成WAV文件，参数: sampleRate=" + sampleRate + 
                      ", channels=" + channels + ", bitsPerSample=" + bitsPerSample + 
                      ", pcmLength=" + pcm.length);
            
            out.write("RIFF".getBytes());
            out.write(intToLE(totalDataLen));
            out.write("WAVE".getBytes());
            out.write("fmt ".getBytes());
            out.write(intToLE(16)); // Subchunk1Size
            out.write(shortToLE((short) 1)); // AudioFormat
            out.write(shortToLE((short) channels));
            out.write(intToLE(sampleRate));
            out.write(intToLE(byteRate));
            out.write(shortToLE((short) (channels * bitsPerSample / 8)));
            out.write(shortToLE((short) bitsPerSample));
            out.write("data".getBytes());
            out.write(intToLE(pcm.length));
            out.write(pcm);
            
            byte[] wavData = out.toByteArray();
            Log.d(TAG, "WAV文件生成成功，大小: " + wavData.length + " 字节");
            return wavData;
            
        } catch (Exception e) {
            Log.e(TAG, "生成WAV文件失败", e);
            e.printStackTrace();
            return new byte[0];
        }
    }
    
    private static byte[] intToLE(int v) {
        return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v).array();
    }
    
    private static byte[] shortToLE(short v) {
        return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(v).array();
    }
} 